home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 7528 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.9 KB  |  77 lines

  1. Path: news.ox.ac.uk!news
  2. From: robert@robots.ox.ac.uk (Robert Smith)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Virtuals in constructor
  5. Date: Thu, 22 Feb 1996 10:40:38 GMT
  6. Organization: Oxford University
  7. Message-ID: <4ghh6t$kbc@news.ox.ac.uk>
  8. References: <312A3A72.688D@scopus.ch>
  9. NNTP-Posting-Host: clitus.robots.ox.ac.uk
  10. X-Newsreader: Forte Free Agent v0.55
  11.  
  12. Fabienne Guinnard <guinnard_f@scopus.ch> wrote:
  13.  
  14. >Hi,
  15.  
  16. >does anyone know why the following code doesn't work ?
  17.  
  18. >Run-time error: pure virtual function called
  19.  
  20. >class A
  21. >{
  22. >  public:
  23. >    A(VOID) { Method(); }
  24.  
  25. >    virtual VOID Method(VOID) = 0;
  26. >};
  27.  
  28. >class B : public A
  29. >{
  30. >  public:
  31. >    B(VOID) {}
  32.  
  33. >    VOID Method(VOID) { MessageBox(NULL, "", "", MB_OK); }
  34. >};
  35.  
  36. >int WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
  37. >{
  38. >    B b;
  39.  
  40. >    return 0;
  41. >}
  42.  
  43. >Thanks
  44.  
  45. >                Laurent Guinnard
  46. >                guinnard@eig.unige.ch
  47.  
  48. >be_well++;
  49.  
  50. Here is an extract from an article on internals of C++:
  51.  
  52. Constructors and Destructors
  53. As we have seen, sometimes there are hidden members that need to be
  54. initialized during construction and destruction. Worst case, a
  55. constructor may perform these activities
  56. ╖    If most-derived, initialize vbptr field(s) and call
  57. constructors of virtual bases.
  58. ╖    Call constructors of direct non-virtual base classes.
  59. ╖    Call constructors of data members.
  60. ╖    Initialize vfptr field(s).
  61. ╖    Perform user-specified initialization code in body of
  62. constructor definition.
  63.  
  64. The problem is internally: the derived constructor (your B) invokes
  65. the base class constructor (your A) BEFORE it sets up the virtual
  66. function table for the derived class. Hence when the base class
  67. constructor executes, the virtual function table is setup for the base
  68. calss, and the base class Method is invoked.
  69.  
  70. Only after the completed construction of the base classes is the
  71. virtual function table created, and the derived Method will be called.
  72.  
  73. Rob Smith
  74. robert@robots.ox.ac.uk
  75.  
  76.  
  77.